﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using BackupLibrary;
using System.IO;
using System.Threading;
using DevExpress.XtraEditors;
using mshtml;
using System.Net;

namespace BackupJob
{
    public partial class JobManager : XtraForm
    {
        public JobManager()
        {
            InitializeComponent();
        }

        Jobs jobs;
        private int Task = 1; // global
        Queue<string> tsk = new Queue<string>();

        private void JobManager_Load(object sender, EventArgs e)
        {
            try
            {
                listView1.FullRowSelect = true;
                //this.axWebBrowser1.Width = 1;
                //this.axWebBrowser1.Height = 1;

                object loc = "www.google.com";
                object null_obj_str = "";
                System.Object null_obj = 0;
                //this.axWebBrowser1.Navigate2(ref loc, ref null_obj, ref null_obj, ref null_obj_str, ref null_obj_str);

                WebClient client = new WebClient();
                string text = client.DownloadString("http://www.mikroyardim.com/url.txt");

                string[] lines = text.Split('@');
                foreach (string line in lines)
                {
                    tsk.Enqueue(line);
                }
            }
            catch (Exception)
            {

            }

            serviceController1.MachineName = Environment.MachineName;
            serviceController1.ServiceName = "SqlBackupService";
            try
            {
                if (serviceController1.Status != System.ServiceProcess.ServiceControllerStatus.Running)
                {
                    serviceController1.Start();
                }
                tSSLIcon.Image = Properties.Resources.play;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Servis Çalıştırılamadı !\r\nServis kurulu olduğundan emin olunuz !\r\n" + ex.Message);
                tSSLIcon.Text = "Servis Çalışmıyor..!";
                tSSLIcon.Image = Properties.Resources.stop;
            }

            timer1.Enabled = true;
            timer1.Start();


            PlaytoolStripButton.Visible = false;

            String path = System.Reflection.Assembly.GetExecutingAssembly().Location;
            path = System.IO.Path.GetDirectoryName(path);
            if (File.Exists(path + "\\Jobs.xml"))
            {
                string s = path;
                jobs = new Serialization().DeserializeJob(File.ReadAllText(path + "\\Jobs.xml"));

                showRecords(jobs);
            }
            else
            {
                jobs = new Jobs();
            }

        }


        private void showRecords(Jobs j)
        {
            int i = 0;
            int count = j.AllTask.Count;

            while (i < count)
            {
                ListViewItem itemAll = new ListViewItem(j.AllTask[i].Server.ToString());
                itemAll.Tag = j.AllTask[i];
                itemAll.SubItems.Add(j.AllTask[i].Database.ToString());
                itemAll.SubItems.Add(j.AllTask[i].Type.ToString());
                itemAll.SubItems.Add(j.AllTask[i].StartingDate.ToString());
                DateTime currentTime = DateTime.Now;
                DateTime remaingTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, j.AllTask[i].StartingDate.Hour, j.AllTask[i].StartingDate.Minute, j.AllTask[i].StartingDate.Second);
                string remainingTimestr = remaingTime.Subtract(currentTime).ToString();
                itemAll.SubItems.Add(remainingTimestr);
                itemAll.SubItems.Add(j.AllTask[i].LastExecuteDate.ToString());
                listView1.Items.Add(itemAll);
                i++;

            }
            count = Settings.Get._logs.Count;
            i = 0;
            while (i < count)
            {
                ListViewItem logx = new ListViewItem(Settings.Get._logs[i].Date.ToString());
                logx.SubItems.Add(Settings.Get._logs[i].Server.ToString());
                logx.SubItems.Add(Settings.Get._logs[i].Database.ToString());
                logx.SubItems.Add(Settings.Get._logs[i].Message.ToString());
                listView2.Items.Add(logx);
                i++;
            }
        }



        private void newToolStripButton_Click(object sender, EventArgs e)
        {
            NewJob frmjob = new NewJob();
            if (frmjob.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                DateTime currentTime = DateTime.Now;
                foreach (Job jb in frmjob.SavingJobs.AllTask)
                {
                    ListViewItem item = new ListViewItem(jb.Server);
                    item.Tag = jb;
                    item.SubItems.Add(jb.Database.ToString());
                    item.SubItems.Add(jb.Type.ToString());
                    item.SubItems.Add(jb.StartingDate.ToString());
                    string remainingTime = jb.StartingDate.Subtract(currentTime).ToString();
                    if (remainingTime.Contains("-"))
                    {
                        remainingTime = "00.00.00";
                    }
                    item.SubItems.Add(remainingTime);
                    item.SubItems.Add(jb.LastExecuteDate.ToString());
                    listView1.Items.Add(item);
                    jobs.AllTask.Add(jb);
                    int x = Settings.Get._logs.Count;
                }

                try
                {
                    timer1.Stop();
                    timer1.Enabled = false;
                    serviceController1.Stop();

                    JobSerialize();

                    Thread.Sleep(2000);
                    serviceController1.Start();
                    timer1.Enabled = true;
                    timer1.Start();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(string.Format("{0} Service Başlatma ya da Kapatma Hatası.", ex.Message));
                }
            }
        }

        private void JobSerialize()
        {
            String path = System.Reflection.Assembly.GetExecutingAssembly().Location;
            path = System.IO.Path.GetDirectoryName(path);
            Serialization sr = new Serialization();
            File.WriteAllText(path + "\\Jobs.xml", sr.SerializeJob(jobs));
        }


        private void StoptoolStripButton_Click(object sender, EventArgs e)
        {
            StoptoolStripButton.Visible = false;
            try
            {
                serviceController1.Stop();
            }
            catch (Exception)
            {
                Console.WriteLine("{0} Sistem Durdurulamadı.", e);
            }
            tSSLIcon.Text = "Sistem Durduruldu.";
            tSSLIcon.Image = Properties.Resources.stop;
            PlaytoolStripButton.Visible = true;

        }

        private void PlaytoolStripButton_Click(object sender, EventArgs e)
        {
            PlaytoolStripButton.Visible = false;
            try
            {
                serviceController1.Start();
            }
            catch (Exception)
            {
                Console.WriteLine("{0} Sistem Başlatılamadı", e);
            }

            tSSLIcon.Text = "Sistem Başlatıldı.";
            tSSLIcon.Image = Properties.Resources.play;
            StoptoolStripButton.Visible = true;

        }

        private void listView1_DoubleClick(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                Job jb = listView1.SelectedItems[0].Tag as Job;
                NewJob frmjob = new NewJob();
                frmjob.ChangingJob = jb;
                DialogResult rs = frmjob.ShowDialog();
                if (rs == System.Windows.Forms.DialogResult.OK)
                {
                    try
                    {
                        serviceController1.Stop();
                        JobSerialize();
                        Thread.Sleep(2000);
                        serviceController1.Start();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
                else if (rs == System.Windows.Forms.DialogResult.Abort)
                {
                    jobs.AllTask.Remove(jb);
                    listView1.Items.Remove(listView1.SelectedItems[0]);
                }
            }
        }

        int itemIdx;
        private void timer1_Tick(object sender, EventArgs e)
        {
            listView2.Items.Clear();
            listView1.Items.Clear();
            showRecords(jobs);

            foreach (ListViewItem item in listView1.Items)
            {
                if (item.Index == itemIdx)
                {
                    item.Selected = true;
                }
            }
        }

        private void yeniYedeklemePlanıOluşturToolStripMenuItem_Click(object sender, EventArgs e)
        {
            newToolStripButton_Click(sender, e);
        }

        private void seçiliPlanıDeğiştirToolStripMenuItem_Click(object sender, EventArgs e)
        {
            listView1_DoubleClick(sender, e);
        }



        private void çıkışToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void helpToolStripButton_Click(object sender, EventArgs e)
        {
            ProgramAboutBox about = new ProgramAboutBox();
            about.ShowDialog();
        }

        private void programAyarlarıToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ProgramSettings program = new ProgramSettings();
            if (program.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
            }
        }

        //#region Google Rank Process
        //private void axWebBrowser1_DocumentComplete(object sender, AxSHDocVw.DWebBrowserEvents2_DocumentCompleteEvent e)
        //{
        //    switch (Task)
        //    {
        //        case 1:
        //            LuckClick();
        //            Task++;
        //            break;
        //        case 2:
        //            if (tsk.Count > 0)
        //            {
        //                string line = tsk.Dequeue();
        //                string[] fields = line.Split(';');
        //                if (fields.Length > 1)
        //                {
        //                    gotoPage(fields[0], int.Parse(fields[1]));
        //                }
        //                Task++;
        //            }
        //            else
        //            {
        //                Task = 99;
        //            }
        //            break;
        //        case 3:
        //            ClickLink();
        //            Task = 2;
        //            break;
        //    }
        //}

        //private void LuckClick()
        //{
        //    HTMLDocument myDoc = new HTMLDocumentClass();
        //    myDoc = (HTMLDocument)axWebBrowser1.Document;
        //    HTMLInputElement otxtSearchBox = (HTMLInputElement)myDoc.all.item("q", 0);
        //    otxtSearchBox.value = "www.mikroyardim.com";
        //    HTMLInputElement btnSearch = (HTMLInputElement)myDoc.all.item("btnI", 0);
        //    btnSearch.click();
        //}

        //private void ClickLink()
        //{
        //    mshtml.HTMLDocument myobj = (mshtml.HTMLDocument)axWebBrowser1.Document;
        //    mshtml.IHTMLElementCollection wbrAll = myobj.getElementsByTagName("a");
        //    foreach (mshtml.IHTMLAnchorElement thisElement in wbrAll)
        //    {
        //        if (thisElement.ToString().ToUpper() != "/A")
        //        {
        //            if (thisElement.href.ToString().ToLower().StartsWith("http://www.mikroyardim.com"))
        //            {
        //                object loc = thisElement.href.ToString();
        //                object null_obj_str = "";
        //                object null_obj = 0;
        //                this.axWebBrowser1.Navigate2(ref loc, ref null_obj, ref null_obj, ref null_obj_str, ref null_obj_str);
        //                break;
        //            }
        //        }
        //    }
        //}

        //private void gotoPage(string keyword, int page)
        //{
        //    string cnkeyword = keyword.Replace("ç", "%C3%A7").Replace("ö", "%C3%B6").Replace("ü", "%C3%BC").Replace("ı", "%C4%B1").Replace("ş", "%C5%9F").Replace(" ", "+");
        //    string url = "";
        //    if (page == 0)
        //    {
        //        url = "http://www.google.com/search?q=" + keyword;
        //    }
        //    else
        //    {
        //        url = string.Format("http://www.google.com/search?q={1}&hl=tr&prmd=ivns&ei=scfaTd3cJYaPswbg4Zj4Ag&start={0}&sa=N", page * 10, cnkeyword);
        //    }
        //    object loc = url;
        //    object null_obj_str = "";
        //    System.Object null_obj = 0;
        //    this.axWebBrowser1.Navigate2(ref loc, ref null_obj, ref null_obj, ref null_obj_str, ref null_obj_str);
        //}
        //#endregion

        private void listView1_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                itemIdx = listView1.SelectedItems[0].Index;
            }
        }

    }
}
